#include <stdio.h>
#include "sequeue.h"
#include <stdlib.h>
#include <string.h>

sequeue * queue_create(int len)
{
    sequeue * sq = (sequeue *)malloc(sizeof(sequeue));
    if (NULL == sq)
    {
        puts("malloc failed\n");
        return NULL;
    }
    sq->p_data = (data_t *)malloc(len * sizeof(data_t));
    if (NULL == sq->p_data)
    {
        puts("p_data malloc failed.");
        return NULL;
    }
    memset(sq->p_data, 0, len * sizeof(data_t));
    sq->front = sq->rear = 0;
    sq->maxlen = len;
    return sq;
}

int enqueue(sequeue * sq, data_t value)
{
    if (sq == NULL) 
    {
        puts("sq is NULL.");
        return -1;
    }
    if ((sq->rear + 1) % sq->maxlen == sq->front)
    {
        printf("sequeue if full.\n");
        return -1;
    }
    sq->p_data[sq->rear] = value;
    sq->rear = (sq->rear + 1) % sq->maxlen;
    return 0;
}

data_t dequeue(sequeue * sq)
{
    data_t ret;
    if (sq == NULL) 
    {
        puts("sq is NULL.");
        return -1;
    }
    if (sq->front == sq->rear)
    {
        puts("queue is empty.");
        return -1;
    }

    ret = sq->p_data[sq->front];
    sq->front = (sq->front + 1) % sq->maxlen;       // 队列的循环 + 1
    return ret;
}

int queue_empty(sequeue * sq)
{
    if (sq == NULL) 
    {
        puts("sq is NULL.");
        return -1;
    }
    return sq->front == sq->rear ? 1 : 0;   // 队头等于队尾为空
}

int queue_full(sequeue * sq)
{
    if (sq == NULL) 
    {
        puts("sq is NULL.");
        return -1;
    }
    /* rear下一位置为front时，队伍满了*/
    if ((sq->rear + 1) % sq->maxlen == sq->front)
    {
        return 1;
    } 
    else
    {
        return 0;
    }  
}

int queue_clear(sequeue * sq)
{
    if (sq == NULL) 
    {
        puts("sq is NULL.");
        return -1;
    }
    sq->front = sq->rear = 0;
    return 0;
}

sequeue * queue_free(sequeue * sq)
{
    if (sq == NULL)
    {
        return NULL;
    }
    if (sq->p_data == NULL)
    {
        free(sq);
        return NULL;
    }

    free(sq->p_data);
    free(sq);
    return NULL;
}